package com.wontube.core.pub.servlet;

import java.io.IOException;
import java.io.InputStreamReader;

import com.wontube.client.pub.ProxyRequest;
import com.wontube.client.pub.ServerResponse;
import com.wontube.core.pub.AppEnvironment;


/**
 * @author yuechao
 *
 */
public final class HttpPostProcessor extends PostProcessor {
	@Override
	protected ProxyRequest readProxyRequest() {
		if(isAnsyncClosed()){
			return null;
		}
		
		StringBuilder sb = new StringBuilder();
		char[] cbuf = new char[4096];
		InputStreamReader reader = null ;
		try {
			reader = new InputStreamReader(this.request.getInputStream(), AppEnvironment.charsetName);
			while (true) {
				int len = reader.read(cbuf, 0, cbuf.length);
				if (len <= 0) {
					break;
				}
				sb.append(cbuf, 0, len);
			}
		} catch (IOException e) {
			this.logger.error(e.toString());
		}  finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					this.logger.error(e.toString());
				}
			}
		}
		
		if (sb.length() == 0) {
			return null;
		}

		ProxyRequest proxyRequest = new ProxyRequest();
		return proxyRequest.fromJosnString(sb.toString());
	}
	
	@Override
	protected void onResponse(ServerResponse result) {
		String json = result.toJsonString();
		this.writer.write(json);
		this.writer.flush();
	}
}
